#pragma once
#include <atomic>
#include <thread>
#include <mutex>
#include <list>
#include <vector>
#include <unordered_map>
#include <functional>
#include <chrono>

namespace HAL {
struct TimerPos {
    int ms = 0;
    int sec = 0;
    int min = 0;
};

class TimerEvent {
    public:
        int id;
        std::string name;
        std::function<void()> callback;
        void setRepeat(bool repeat) { this->repeat = repeat; } 
        void setCancel(bool cancelled) { this->cancelled = cancelled; }
    private:
        friend class TimerWheel;
        int interval_ms = 10;
        bool cancelled = false;
        bool repeat = false;
        TimerPos pos;
};

class TimerWheel {
public:
    TimerWheel(int tick_ms = 10);
    ~TimerWheel();

    void Start();
    void Stop();

    bool AddTask(int delay_ms, TimerEvent &ev);
    void CancelTask(int id);

private:
    void AddTaskNoLock(int delay_ms, TimerEvent &ev);
    void ThreadFunc();
    void Tick();
    void TickSecondWheel();
    void TickMinuteWheel();

    TimerPos CalcPosition(int delay_ms);

private:
    // 三层时间轮容器
    std::vector<std::list<TimerEvent>> wheel_ms_;
    std::vector<std::list<TimerEvent>> wheel_sec_;
    std::vector<std::list<TimerEvent>> wheel_min_;

    // 任务索引表（用于取消任务）
    std::unordered_map<int, TimerEvent*> task_map_;

    // 当前指针
    std::size_t cursor_ms_  = 0;
    std::size_t cursor_sec_ = 0;
    std::size_t cursor_min_ = 0;

    // 线程控制
    std::atomic<bool> _running = false;
    std::thread _thread_working;
    std::mutex _mutex_working;

    int _interval_ms = 10;   // tick 间隔 
};

}